package com.person.jc.service.car;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.person.jc.service.Service;
import com.person.jc.utils.Utils;

public class BdCarUseService extends Service {
	
	public static final BdCarUseService me = new BdCarUseService();
	
	public List<Record> getList(Map<String,Object> map){
		String temp = "";
		List<Object> params = new ArrayList<Object>();
		StringBuffer sql= new StringBuffer("select *,date_format(use_date, '%Y-%m-%d %H:%i:%s') use_date_ from bs_car_use_log where oper_user = ? ");
		params.add(map.get("operUser"));
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("carCode")))){
			sql.append(" and car_no = ?");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("logId")))){
			sql.append(" and log_id = ?");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("driver")))){
			sql.append(" and driver like '%"+ temp +"%'");
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("useStatus")))){
			if("1".equals(temp)){
				sql.append(" and return_addr is null");
			}else{
				sql.append(" and return_addr is not null");
			}
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("startDate")))){
			sql.append(" and date_format(use_date, '%Y-%m-%d') >= ?");
			params.add(temp);
		}
		if(Utils.isNotEmpty(temp = String.valueOf(map.get("endtDate")))){
			sql.append(" and date_format(use_date, '%Y-%m-%d') <= ?");
			params.add(temp);
		}
		sql.append(" order by use_date desc");
		return Db.find(sql.toString(),Utils.getObjParam(params));
	}
	
	public long checkName(String carCode, String logId){
		String sql = " select count(1) from bs_car_use_log where return_addr is null and car_no = ?";
		if(Utils.isNotEmpty(logId)){
			sql += " and log_id = '"+ logId +"'";
		}
		return Db.queryLong(sql, carCode);
	}
	
	public void save(Map<String,Object> map){
		String sql = "insert into bs_car_use_log(car_no,use_date,destination,use_to,other_user,oper_user,remark,driver,start_mileage) values";
		sql += "(?,?,?,?,?,?,?,?,?)";
		List<Object> params = new ArrayList<Object>();
		params.add(map.get("carNo"));
		params.add(map.get("useDate"));
		params.add(map.get("destination"));
		params.add(map.get("useTo"));
		params.add(map.get("otherUser"));
		params.add(map.get("operUser"));
		params.add(map.get("remark"));
		params.add(map.get("driver"));
		params.add(map.get("startMileage"));
		Db.update(sql, Utils.getObjParam(params));
		super.setCRUD("用车申请", "C", "新增用车申请："+map.get("carNo"));
	}
	
	public void delete(String logId){
		String sql = "delete from bs_car_use_log where log_id = ? ";
		Db.update(sql, logId);
		super.setCRUD("用车申请", "D", "删除用车申请："+logId);
	}
}
